package com.lottery.im.module.contact.adapter;

import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.lottery.im.R;
import com.lottery.im.module.tim.model.ContactFriend;
import com.lottery.im.module.tim.model.ContactGroup;
import com.lottery.im.util.transformations.CropCircleTransformation;
import java.util.List;

public class ContactAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {

  public static final int TYPE_LEVEL_0 = 0;
  public static final int TYPE_LEVEL_1 = 1;

  private boolean isExpand = false;

  /**
   * Same as QuickAdapter#QuickAdapter(Context,int) but with
   * some initialization data.
   *
   * @param data A new list is created out of this one to avoid mutable list
   */
  public ContactAdapter(List<MultiItemEntity> data) {
    super(data);
    addItemType(TYPE_LEVEL_0, R.layout.item_contact_expandable_header);
    addItemType(TYPE_LEVEL_1, R.layout.item_contact_friend);
  }

  @Override protected void convert(final BaseViewHolder helper, MultiItemEntity item) {

    switch (helper.getItemViewType()) {
      case TYPE_LEVEL_0:

        final ContactGroup contactGroup = (ContactGroup) item;
        helper.setText(R.id.tv_group_name, contactGroup.groupName)
            .setText(R.id.tv_friend_num, contactGroup.memberNum + "人")
            .setImageResource(R.id.iv_switch, contactGroup.isExpanded() ? R.drawable.icon_group_open
                : R.drawable.icon_group_close);
        helper.itemView.setOnClickListener(v -> {

          int pos = helper.getAdapterPosition();
          if (contactGroup.isExpanded()) {
            collapse(pos);
            isExpand = false;
          } else {
            expand(pos);
            isExpand = true;
          }
        });
        break;
      case TYPE_LEVEL_1:

        final ContactFriend contactFriend = (ContactFriend) item;

        ImageView ivPortrait = helper.getView(R.id.iv_portrait);
        Glide.with(mContext)
            .load(contactFriend.friendProfile.getAvatarUrl())
            .apply(new RequestOptions()
                .bitmapTransform(new CropCircleTransformation())
                .placeholder(R.drawable.icon_conversation_de)
                .error(R.drawable.icon_conversation_de))
            .into(ivPortrait);
        helper.setText(R.id.tv_name, contactFriend.friendProfile.getName());

        break;
    }
  }

  public boolean isExpand() {
    return isExpand;
  }
}